package web.servlet;

import dao.UserDao;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/LoginServlet2")
public class LoginServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置从request中取得的值或从数据库中取出的值
        request.setCharacterEncoding("utf-8");
        //获取所有请求的参数
//        Map<String, String[]> map = request.getParameterMap();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String check_code = request.getParameter("check_code");
        System.out.println(check_code);

        //创建session对象
        HttpSession session = request.getSession();
        //拿到验证码数据
        String checkCode = (String)session.getAttribute("check_session");
        System.out.println(checkCode);
        //拿到之后删除session中存储的验证码
        session.removeAttribute("check_session");

        //比较服务器生成的验证码和用户输入的验证码是否相等
        if (checkCode.equalsIgnoreCase(check_code)) {
            //创建user对象并赋值
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);

            //创建操作数据库表类的对象
            UserDao dao = new UserDao();

            //将user传参,查询并返回一个user对象
            User loginUser = dao.login(user);

            if (loginUser != null) {
                //登录成功
                session.setAttribute("user", username);
                //重定向到success.jsp
                response.sendRedirect(request.getContextPath() + "/success.jsp");
            } else {
                //登录失败
                //存储提示信息到request
                request.setAttribute("login_user", "用户名或密码错误");
                //转发到登录页面
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
            //使用不了BeanUtils工具类,因参数中有验证码,无法对user进行全部数据封装
//        //使用BeanUtils工具类给user对象的属性赋值
//        try {
//            BeanUtils.populate(user,map);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
        } else {
            //验证码不一致
            //存储提示信息到request
            request.setAttribute("cc_error", "验证码错误");
            //转发到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
